package com.kye.express.business.waybill_take_photo;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.waybill_take_photo.history.WaybillTakePhotoHistoryActivity;
import com.kye.express.business.waybill_take_photo.yunmai.CameraActivity;
import com.kye.express.databinding.ActivityWaybillTakePhotoBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.waybill_take_photo.UploadWaybillPictureResultBean;
import com.kye.model.bean.waybill_take_photo.WaybillPhotograhbean;
import com.kye.model.download.DownloadManager;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 运单拍照
 */
public class WaybillTakePhotoActivity extends BaseToolbarActivity implements WaybillTakePhotoActivityContract.WaybillTakePhotoActivityView {
    private static final int REQUEST_CODE_ADD_WAYBILL = 1;
    private ActivityWaybillTakePhotoBinding mBinding;
    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private WaybillTakePhotoActivityContract.WaybillTakePhotoActivityViewPresenter mPresenter;
    private RxPermissions mPermissions;
    private List<WaybillPhotograhbean> mWaybillList = new ArrayList<WaybillPhotograhbean>();
    private Dialog mDialog;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, WaybillTakePhotoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_waybill_take_photo);
        mPresenter = new WaybillTakePhotoActivityContract.WaybillTakePhotoActivityViewPresenter(this);
        mPresenter.bind(this);
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        setTitle(getString(R.string.waybill_take_photo_title));
        mPermissions = new RxPermissions(this);
        mPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            
                        } else {
                            ToastManager.show(WaybillTakePhotoActivity.this, R.string.waybill_take_photo_no_permissions, Toast.LENGTH_SHORT);
                            finish();
                        }
                    }
                });
        initView();
        initEvent();
    }

    private void addAddItemData() {
        if (mWaybillList.size() < 9) {
            mWaybillList.add(new WaybillPhotograhbean());
        }
    }

    private void initView() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(WaybillPhotograhbean.class, new WaybillTakePhotoImagetemViewBinder(this, this));
        mBinding.recyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        mBinding.recyclerview.addItemDecoration(new SpaceItemDecoration(ScreenUtils.dp2px(this, 8)));
        addAddItemData();
        mDatas.addAll(mWaybillList);
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    private void initEvent() {
        RxView.clicks(mBinding.btnUpload)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mWaybillList.size() > 0) {
                            List<WaybillPhotograhbean> waybillList = new ArrayList<WaybillPhotograhbean>();
                            if (mWaybillList.size() < 9) {
                                for (int i = 0; i < mWaybillList.size() - 1; i++) {
                                    waybillList.add(mWaybillList.get(i));
                                }
                            } else {
                                waybillList.addAll(mWaybillList);
                            }
                            if (waybillList.size() > 0) {
                                mPresenter.uploadWaybills(waybillList);
                            } else {
                                showEmptyDialog();
                            }
                        } else {
                            showEmptyDialog();
                        }
                    }
                });
    }

    private void showEmptyDialog() {
        new MaterialDialog.Builder(this)
                .content(R.string.waybill_take_photo_waybill_is_null)
                .negativeText(R.string.common_know)
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_waybill_take_photo, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_record:
                WaybillTakePhotoHistoryActivity.startActivity(this);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    @Override
    public void onComplete() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onLoading() {
        if (mDialog == null) {
            mDialog = new KyeProgressDialog.Builder(this).build();
        }
        mDialog.show();
    }

    @Override
    public void onLoaded(List<UploadWaybillPictureResultBean> uploadWaybillPictureResultBeans) {
        ToastManager.show(this, R.string.common_upload_successfully, Toast.LENGTH_SHORT);
        finish();
    }

    @Override
    public void onOtherError(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onApiError(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }


    @Override
    public void onAddWallbillButtonClicked() {
        Intent intent = new Intent(this, CameraActivity.class);
        List<WaybillPhotograhbean> waybillList = new ArrayList<WaybillPhotograhbean>();
        for (int i = 0; i < mWaybillList.size() - 1; i++) {
            waybillList.add(mWaybillList.get(i));
        }
        intent.putExtra(CameraActivity.ARG_DATA, (Serializable) waybillList);
        startActivityForResult(intent, REQUEST_CODE_ADD_WAYBILL);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_ADD_WAYBILL && data != null) {
            mWaybillList = (List<WaybillPhotograhbean>) data.getSerializableExtra(CameraActivity.ARG_DATA_RESULT);
            addAddItemData();
            mDatas.clear();
            mDatas.addAll(mWaybillList);
            mAdapter.notifyDataSetChanged();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.bottom = space;
        }

    }
}
